package com.cscp.javastudy.juc.threaddemo;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo1 {

    public static void main(String[] args) {
        //停车位3个
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <= 6; i++) {//6辆车抢车位
            new Thread(()->{
                try {
                    semaphore.acquire();//得到，假设如果已经满了，等待，等待被释放为止
                    System.out.println(Thread.currentThread().getName()+"抢到车位");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName()+"离开车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();//释放，会将当前的信号释放+1，然后唤醒等待的线程
                }
            }, String.valueOf(i)).start();
        }
    }

}
